import requests
import json
from handle_excel import HandleExcel


# 登录crm后台账号以获取token
def get_crm_token(username, password):
    url = "https://crm.hongsong.info/gateway/api/fj-staff/account/v1/login"

    payload = json.dumps({
        "username": username,
        "password": password
    })
    headers = {
        'loginsource': 'crm',
        'userid': 'null',
        'token': '[object Object]',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    token = response.json()['data']['token']
    return token


# crm后台直播场次搜索接口，根据roundId获取roomId和场次name
def get_roomId_and_name(roundId, token):
    url = "https://crm.hongsong.info/gateway/api/fjkt-crm-course-ui-interfaces/v2/course/round-page"

    payload = json.dumps({
        "roundId": roundId,
        "current": 1,
        "pageSize": 20
    })
    headers = {
        'authority': 'crm.hongsong.info',
        'loginsource': 'crm',
        'token': token,
        'userid': 'null',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    roundName = response.json()['data']['data'][0]['roundName']
    roomId = response.json()['data']['data'][0]['streamKey']
    return roundName, roomId


# 通过roomID获取直播间评论数量
def get_comment_nums(roomId, token):
    url = "https://crm.hongsong.info/crmapi/api/edu-fengjin-admin-web/chart/chatMessages"

    payload = json.dumps({
        "data": {
            "current": 1,
            "pageSize": 20,
            "roundId": 12,
            "roomId": roomId
        }
    })
    headers = {
        'authority': 'crm.hongsong.info',
        'loginsource': 'crm',
        'token': token,
        'userid': 'null',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'content-type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    try:  # 情况正常，返回数据
        comment_nums = response.json()['data']['totalCount']
        return comment_nums
    except KeyError:  # 有异常，返回False
        return False


def get_crm_live_data():
    # 读取token配置文件中的token
    with open('./token.json', 'r') as f:
        data = json.load(f)
    token = data['token']

    hde = HandleExcel()  # 实例化excel处理工具类
    round_ids = hde.get_columns_value("C")[1::]  # 获取excel中的roundId
    round_ids_not_none = []
    for i in round_ids:
        if i is not None:
            round_ids_not_none.append(i)
    print(round_ids_not_none)
    print('长度', len(round_ids_not_none))

    for round_id in round_ids_not_none:
        list_crm_data = []
        name, roomId = get_roomId_and_name(round_id, token)
        nums = get_comment_nums(roomId, token)
        if nums is False:  # 为false，则走登录接口，获取最新的token，并将其写入文件
            print(1)
            token = get_crm_token('fanchao@hongsong.club', 'k50ckd')
            data['token'] = token
            with open('./token.json', 'w') as f:
                f.write(json.dumps(data))
            nums = get_comment_nums(roomId, token)

        print(name, roomId, nums)
        list_crm_data.append(name)
        list_crm_data.append(roomId)
        list_crm_data.append(nums)

        # 获取对应roundId所位于的行号
        row_num = hde.get_rows_number(round_id, 'C')
        hde.excel_write_data(row_num, 4, list_crm_data[0])  # 写入直播场次名到excel
        hde.excel_write_data(row_num, 2, list_crm_data[1])  # 写入roomId到excel
        hde.excel_write_data(row_num, 7, list_crm_data[2])  # 写入评论数到excel

# get_crm_live_data()
